#include "dictpackmgr.h"
#include "cfgmgr.h"

DictPackManager::DictPackManager() {
    connect_dictpacks();
}

bool DictPackManager::get_candidate_words(const wxString& word, wxArrayString& words, int limit) {
    for ( int i=0; i<_dictdbquery_ptr_a.Count(); i++ ) {
        _dictdbquery_ptr_a[i]->query_word(word, words, limit);
    }
    
    words.Sort();
    
    return true;
}

bool DictPackManager::get_expl(const wxString& word, wxArrayString& words, int limit) {
    for ( int i=0; i<_dictdbquery_ptr_a.Count(); i++ ) {
        _dictdbquery_ptr_a[i]->query_word(word, words, limit);
    }
    
    words.Sort();
    
    return true;
}

/*
select w_o_word, w_l_word from pack1.words
where pack1.words.w_o_word glob '我*' 
union all select w_o_word, w_l_word from pack2.words where pack2.words.w_o_word glob '我*'
*/
bool DictPackManager::connect_dictpacks() {
    wxArrayString dictpackfn_a;
    wxDir::GetAllFiles(ConfigManager::get().product_dictpack_dir.GetPath(),&dictpackfn_a,_T("*.dictpack"),wxDIR_FILES);

    try {
        for ( int i=0; i<dictpackfn_a.Count(); i++ ) {
            DictDBQuery* p_dictdb = new DictDBQuery(dictpackfn_a[i]);
            _dictdbquery_ptr_a.Add(p_dictdb);
        }
    } catch (wxSQLite3Exception& e) {
        wxLogError(_T("%s: %s, %d"), __DAO_FUNC_NAME__.c_str(), e.GetMessage().c_str(), e.GetErrorCode());
        return false;
    }
    
    return true;
}

bool DictPackManager::disconnect_dictpacks() {
    try {
        for ( int i=0; i<_dictdbquery_ptr_a.Count(); i++ ) {
            delete _dictdbquery_ptr_a[i]);
        }
        
        _dictdbquery_ptr_a.Clear();
    } catch (wxSQLite3Exception& e) {
        wxLogError(_T("%s: %s, %d"), __DAO_FUNC_NAME__.c_str(), e.GetMessage().c_str(), e.GetErrorCode());
        return false;
    }
    
    return true;
}

int DictPackManager::reconnect_dictpacks() {
    disconnect_dictpacks();
    return connect_dictpacks();
}
